package com.jsbs.iam.ident.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jsbs.iam.common.core.utils.DateUtils;
import com.jsbs.iam.common.core.utils.UUIDUtils;
import com.jsbs.iam.ident.auth.TokenInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

/**
 * JWT看起来是这个样子的：aaaaaa.bbbbbb.ccccccc
 */
public class TokenHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenHelper.class);

    /**
     * 基于服务端sso登录信息创建对应的服务端用户令牌
     */
    public static TokenInfo createToken (String phone, String userCode, String ip, String jwtSecret){
        LocalDateTime createTime = LocalDateTime.now();
        String token = JWT.create().withClaim("phone", phone)
                .withClaim("userCode", userCode)
                .withClaim("ip", ip)
                .withClaim("r", UUIDUtils.uuid())
                .withIssuedAt(DateUtils.asDate(createTime))
                .sign(Algorithm.HMAC256(jwtSecret));
        TokenInfo ret = new TokenInfo(phone, userCode, createTime, token, ip);
        return ret;
    }

    /**
     * 验证令牌是否合法
     */
    public static TokenInfo validateToken (String token, String jwtSecret){
        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(jwtSecret)).build().verify(token);
            String phone = decodedJWT.getClaim("phone").asString();
            String userCode = decodedJWT.getClaim("userCode").asString();
            String ip = decodedJWT.getClaim("ip").asString();
            LocalDateTime createTime = DateUtils.asLocalDateTime(decodedJWT.getIssuedAt());
            TokenInfo ret = new TokenInfo(phone, userCode, createTime, token, ip);
            return ret;
        }catch (Exception e){
            LOGGER.warn("Token验证失败", e);
            return null;
        }
    }
}
